package com.niguang.labour.admin.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.niguang.labour.admin.TeamListVo;
import com.niguang.labour.admin.entity.*;
import com.niguang.labour.admin.enums.ManageTypeEnum;
import com.niguang.labour.admin.service.*;
import com.niguang.labour.common.constant.ResultCode;
import com.niguang.labour.common.pojo.Result;
import com.niguang.labour.common.util.ApiTokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 'work.v_personSite' is not BASE TABLE 前端控制器
 * </p>
 *
 * @author
 * @since 2018-06-10
 */
@RestController
@RequestMapping("/workTeamUser/")
public class WorkTeamUserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private WorkTeamUserService workTeamUserService;

    @Autowired
    private AdminLaborUserService adminLaborUserService;

    @Autowired
    private WorkSiteUserService workSiteUserService;

    @Autowired
    private WorkLaborCompanyService laborCompanyService;
    @Autowired
    private ApiTokenUtils apiTokenUtils;

    @Autowired
    private WorkQiyeSiteService workQiyeSiteService;

    @Resource
    private WorkTypeService workTypeService;

    @Resource
    private WorkAppUserService workAppUserService;

    @Resource
    private WorkReformUserService workReformUserService;

    @Resource
    private WorkWechatUserService wechatUserService;


    /**
     * 班组增加成功
     *
     * @param workTeamUser
     * @return
     */
    @PostMapping("addTeamUser")
    @Transactional(rollbackFor = Exception.class)
    public Result addTeamUser(@Valid WorkTeamUser workTeamUser) {
        final Long siteId = workTeamUser.getSiteId();

        Long userId = apiTokenUtils.getUserId();

        Long teamUserId = workTeamUser.getTeamUserId();

        AdminLaborUser adminLaborUser = adminLaborUserService.selectById(userId);
        workTeamUser.setLaborCorompanyId(adminLaborUser.getLaborCompanyId());
        workTeamUser.setUserId(userId);
        WorkQiyeSite workQiyeSite = workQiyeSiteService.selectById(siteId);
        if (ObjectUtils.isEmpty(workQiyeSite) || workQiyeSite.getStatus() == 2) {
            return Result.build(ResultCode.PARAM_ERROR, "项目不存在或已结束");
        }
        EntityWrapper<WorkType> typeEntityWrapper = new EntityWrapper<>();
        typeEntityWrapper.eq(WorkType.NAME, "班组管理人").last("limit 1");
        WorkType workType = workTypeService.selectOne(typeEntityWrapper);
        if (ObjectUtils.isEmpty(workType)) {
            return Result.build(ResultCode.PARAM_ERROR, "[班组管理人]类型未配置~");
        }
        workTeamUser.setWorkTypeId(workType.getId());
        // 检测当前添加人是否是 班组长
        EntityWrapper<WorkTeamUser> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq(WorkTeamUser.TEAM_USER_ID, teamUserId).eq(WorkTeamUser.SITE_ID, siteId).eq(WorkTeamUser.DEL_FLAG, 0);
        List<WorkTeamUser> workTeamUserList = workTeamUserService.selectList(entityWrapper);
        if (CollectionUtils.isNotEmpty(workTeamUserList)) {
            WorkTeamUser workTeamUser1 = workTeamUserList.get(0);
            return Result.build(ResultCode.SUCCESS, "员工已是此工地[" + workTeamUser1.getBzName() + "]员工，不可再添加为班组长~");
        }

        try {
            boolean insert = workTeamUserService.insert(workTeamUser);
            if (insert) {
                // ---------------------------- 存入工地员工表 start----------------------------------
                WorkLaborCompany workLaborCompany = laborCompanyService.selectById(adminLaborUser.getLaborCompanyId());
                WorkSiteUser workSiteUser = new WorkSiteUser(teamUserId, workQiyeSite.getQiyeId(), siteId, ManageTypeEnum.BZ_DESC.getIndex(), workType.getId(),
                        workLaborCompany.getLaborName(), adminLaborUser.getLaborCompanyId(), workTeamUser.getId(), workTeamUser.getMonthSalary(),
                        workTeamUser.getStartSalaryDate());
                boolean insert1 = workSiteUserService.insert(workSiteUser);


                WorkAppUser workAppUser = workAppUserService.selectById(workTeamUser.getTeamUserId());
                if (!ObjectUtils.isEmpty(workAppUser)) {
                    EntityWrapper<WorkReformUser> entityWrapper2 = new EntityWrapper<>();
                    entityWrapper2.eq(WorkReformUser.SITE_ID, siteId).eq(WorkReformUser.USER_PHONE, workAppUser.getUserPhone())
                            .eq(WorkReformUser.DEL_FLAG, 0);
                    int count = workReformUserService.selectCount(entityWrapper2);
                    if (count == 0) {
                        EntityWrapper<WorkWechatUser> entityWrapper1 = new EntityWrapper<>();
                        entityWrapper1.eq(WorkWechatUser.USER_PHONE, workAppUser.getUserPhone());
                        WorkWechatUser workWechatUser = wechatUserService.selectOne(entityWrapper1);
                        if (ObjectUtils.isEmpty(workWechatUser)) {
                            workWechatUser = new WorkWechatUser();
                        }

                        WorkReformUser workReformUser = new WorkReformUser(workTeamUser.getSiteId(),
                                workTeamUser.getTeamUserId(), workAppUser.getUserName(), workAppUser.getUserPhone(),
                                workTeamUser.getBzName(), 1, "整改人", workWechatUser.getUnionId(), workWechatUser.getOpenId());
                        workReformUserService.insert(workReformUser);
                    }
                }


                // ---------------------------- 存入工地员工表 end--------------------------------------
                return Result.build(ResultCode.SUCCESS, "班组长添加成功~");
            }
        } catch (Exception e) {
            logger.error("劳务公司增加班组长失败：{}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return Result.failed();
    }


    /**
     * 查询班组列表
     *
     * @param page
     * @return
     */
    @GetMapping("getTeamList")
    public Result getTeamList(Page<TeamListVo> page, @NotNull @RequestParam Long siteId) {
        return Result.build(ResultCode.SUCCESS, "班组列表查询成功！",
                workTeamUserService.getTeamList(page, siteId));
    }

    /**
     * 编辑班组
     *
     * @param workTeamUser
     * @return
     */
    @PostMapping("modifTeamUser")
    @Transactional(rollbackFor = Exception.class)
    public Result modifTeamUser(@Valid WorkTeamUser workTeamUser) {
        WorkTeamUser workTeamUser1 = workTeamUserService.selectById(workTeamUser.getId());
        if (ObjectUtils.isEmpty(workTeamUser1)) {
            return Result.build(ResultCode.PARAM_ERROR, "修改ID[" + workTeamUser.getId() + "]不存在~");
        }
        // 检测当前添加人是否是 班组长
        EntityWrapper<WorkTeamUser> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq(WorkTeamUser.TEAM_USER_ID, workTeamUser.getTeamUserId()).eq(WorkTeamUser.SITE_ID, workTeamUser.getSiteId())
                .notIn(WorkTeamUser.ID, workTeamUser.getId());
        List<WorkTeamUser> workTeamUserList = workTeamUserService.selectList(entityWrapper);
        if (CollectionUtils.isNotEmpty(workTeamUserList)) {
            WorkTeamUser workTeamUser2 = workTeamUserList.get(0);
            return Result.build(ResultCode.SUCCESS, "员工已是此工地[" + workTeamUser2.getBzName() + "]班组长，不可修改~");
        }
        // 判断选择员工是否在班组成员里
        boolean isTeamUser = false;
        List<WorkSiteUser> siteUserList = workSiteUserService.getSiteUserByUserTeamId(workTeamUser.getTeamUserId(), workTeamUser.getId());
        if (CollectionUtils.isNotEmpty(siteUserList)) {
            isTeamUser = siteUserList.stream().filter(p -> p.getManageType().equals(ManageTypeEnum.YG_DESC.getIndex())).count() > 0;
        }
        try {

            EntityWrapper<WorkSiteUser> entityWrapper4 = new EntityWrapper<>();
            entityWrapper4.eq(WorkSiteUser.TEAM_ID, workTeamUser.getId()).eq(WorkSiteUser.SITE_ID, workTeamUser.getSiteId())
                    .eq(WorkSiteUser.USER_ID, workTeamUser.getTeamUserId()).eq(WorkSiteUser.MANAGE_TYPE, ManageTypeEnum.BZ_DESC.getIndex());
            int count = workSiteUserService.selectCount(entityWrapper4);
            if (count > 0) {
                // 此用户已在本班组是班组长
                EntityWrapper<WorkSiteUser> entityWrapper3 = new EntityWrapper<>();
                entityWrapper3.eq(WorkSiteUser.TEAM_ID, workTeamUser.getId()).eq(WorkSiteUser.MANAGE_TYPE, ManageTypeEnum.BZ_DESC.getIndex());
                WorkSiteUser siteUser1 = new WorkSiteUser();
                siteUser1.setManageType(ManageTypeEnum.BZ_DESC.getIndex());
                siteUser1.setDelFlag(1);
                workSiteUserService.update(siteUser1, entityWrapper3);
                entityWrapper3.eq(WorkSiteUser.USER_ID, workTeamUser1.getTeamUserId());
                siteUser1.setDelFlag(0);
                workSiteUserService.update(siteUser1, entityWrapper3);
                workTeamUserService.updateById(workTeamUser);
                return Result.build(ResultCode.SUCCESS, "修改班组长成功~");
            }

            if (!workTeamUser1.getTeamUserId().equals(workTeamUser.getTeamUserId())) {
                // 选择班组长不在班组
                EntityWrapper<WorkSiteUser> entityWrapper3 = new EntityWrapper<>();
                entityWrapper3.eq(WorkSiteUser.TEAM_ID, workTeamUser.getId())
                        .eq(WorkSiteUser.USER_ID, workTeamUser1.getTeamUserId()).eq(WorkSiteUser.MANAGE_TYPE, ManageTypeEnum.BZ_DESC.getIndex());
                WorkSiteUser siteUser1 = new WorkSiteUser();
                siteUser1.setManageType(ManageTypeEnum.BZ_DESC.getIndex());
                siteUser1.setDelFlag(1);
                workSiteUserService.update(siteUser1, entityWrapper3);
            }


            if (isTeamUser) {
                // 选择人员是本班组员工，提升为班组长
                EntityWrapper<WorkSiteUser> entityWrapper2 = new EntityWrapper<>();
                entityWrapper2.eq(WorkSiteUser.TEAM_ID, workTeamUser.getId())
                        .eq(WorkSiteUser.USER_ID, workTeamUser.getTeamUserId());
                WorkSiteUser siteUser = new WorkSiteUser();
                siteUser.setManageType(ManageTypeEnum.BZ_DESC.getIndex());
                siteUser.setDelFlag(0);
                siteUser.setCreateUserId(null);
                workSiteUserService.update(siteUser, entityWrapper2);
            } else {
                if (!workTeamUser1.getTeamUserId().equals(workTeamUser.getTeamUserId())) {
                    // 插入新班组员工
                    WorkSiteUser workSiteUser = new WorkSiteUser(workTeamUser.getTeamUserId(), null, workTeamUser.getSiteId(),
                            ManageTypeEnum.BZ_DESC.getIndex(), workTeamUser1.getWorkTypeId(), null,
                            workTeamUser1.getLaborCorompanyId(), workTeamUser.getId(), workTeamUser.getMonthSalary(),
                            workTeamUser.getStartSalaryDate());
                    workSiteUserService.insert(workSiteUser);
                }
            }
            if (!workTeamUser1.getTeamUserId().equals(workTeamUser.getTeamUserId())) {
                EntityWrapper<WorkSiteUser> siteUserEntityWrapper = new EntityWrapper<>();
                siteUserEntityWrapper.eq(WorkSiteUser.TEAM_ID, workTeamUser.getId()).isNotNull(WorkSiteUser.CREATE_USER_ID);
                workSiteUserService.update(new WorkSiteUser(workTeamUser.getTeamUserId()), siteUserEntityWrapper);
            }
            workTeamUserService.updateById(workTeamUser);

            return Result.build(ResultCode.SUCCESS, "修改班组长成功~");
        } catch (Exception e) {
            logger.error("编辑班组长失败：{}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return Result.failed();
    }

    /**
     * 删除班组长
     *
     * @param teamId
     * @return
     */
    @GetMapping("delTeamUser")
    @Transactional(rollbackFor = Exception.class)
    public Result delTeamUser(@NotNull @RequestParam Long teamId) {

        WorkTeamUser workTeamUser = workTeamUserService.selectById(teamId);
        if (ObjectUtils.isEmpty(workTeamUser)) {
            return Result.build(ResultCode.PARAM_ERROR, "班组长id[" + teamId + "]不存在！");
        }

        EntityWrapper<WorkSiteUser> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq(WorkSiteUser.TEAM_ID, teamId).eq(WorkSiteUser.DEL_FLAG, 0)
                .notIn(WorkSiteUser.MANAGE_TYPE, 2);
        int count = workSiteUserService.selectCount(entityWrapper);
        if (count > 0) {
            return Result.build(ResultCode.PARAM_ERROR, "班组长名下已设置员工，不可删除！");
        }
        boolean update = false;
        try {
            update = workTeamUserService.updateById(new WorkTeamUser(teamId, 1));
            EntityWrapper<WorkSiteUser> entityWrapper1 = new EntityWrapper<>();
            entityWrapper1.eq(WorkSiteUser.TEAM_ID, teamId);
            workSiteUserService.delete(entityWrapper1);

            /*WorkAppUser workAppUser = workAppUserService.selectById(workTeamUser.getUserId());
            if (!ObjectUtils.isEmpty(workAppUser)) {
                EntityWrapper<WorkReformUser> reformUserEntityWrappe = new EntityWrapper<>();
                reformUserEntityWrappe.eq(WorkReformUser.SITE_ID, workTeamUser.getSiteId()).eq(WorkReformUser.USER_PHONE, workAppUser.getUserPhone());
                workReformUserService.delete(reformUserEntityWrappe);
            }*/

        } catch (Exception e) {
            logger.error("删除班组长失败：{}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return Result.build(update ? ResultCode.SUCCESS : ResultCode.FAILED,
                update ? "删除班组成功!" : "删除班组失败！");
    }

    /**
     * 获取用户名下已设置的班组
     *
     * @return
     */
    @GetMapping("getTeamSetUser")
    public Result getTeamSetUser(@NotNull @RequestParam String siteId) {
        return workTeamUserService.getTeamSetUser(siteId);
    }

    /**
     * 获取班组列表
     *
     * @param teamId
     * @param page
     * @return
     */
    @GetMapping("getTeamListUser")
    public Result getTeamListUser(@NotNull @RequestParam String teamId, Page<Map<String, Object>> page) {
        return workTeamUserService.getTeamListUser(page, teamId);
    }

}
